const moment = require('moment');

module.exports = (db, DataTypes) => {
  return db.define('InspectionFile', {
    oid: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false,
      set(index) {  // 当年的index
        let date = moment();
        let year = date.year();
        this.setDataValue('oid', `XL-JL-${index}-${year}`);
      }
    },
    title: DataTypes.STRING,
    type: DataTypes.STRING,
    isAbnormal: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },
    abnormalRecord: DataTypes.TEXT,
    daySignatory: DataTypes.STRING,  // 白班签字
    nightSignatory: DataTypes.STRING, // 夜班签字
    d1Signatory: DataTypes.STRING,  // 白周1
    d2Signatory: DataTypes.STRING,  // 白周2
    d3Signatory: DataTypes.STRING,  // 白周3
    d4Signatory: DataTypes.STRING,  // 白周4
    d5Signatory: DataTypes.STRING,  // 白周5
    d6Signatory: DataTypes.STRING,  // 白周6
    d7Signatory: DataTypes.STRING,  // 白周7
    n1Signatory: DataTypes.STRING,  // 夜周1
    n2Signatory: DataTypes.STRING,  // 夜周2
    n3Signatory: DataTypes.STRING,  // 夜周3
    n4Signatory: DataTypes.STRING,  // 夜周4
    n5Signatory: DataTypes.STRING,  // 夜周5
    n6Signatory: DataTypes.STRING,  // 夜周6
    n7Signatory: DataTypes.STRING,  // 夜周7
    superSignatory: DataTypes.STRING, // 博维签字
    createdTime: {
      type: DataTypes.STRING,
      set(value) {
        let date = moment();
        let year = date.year();
        let month = date.month() + 1;
        let day = date.date();   // todo: momentjs里面要获取某月的某一天要用date，注意！
        this.setDataValue('createdTime', `${year}年${month}月${day}日`);
      }
    },
    createdAt: DataTypes.DATE,
    updatedAt: DataTypes.DATE,
  }, {
    hooks: {
      /**
       *
       * @param inspectionFile
       * 自动生成检查单的所有记录
       */
      async afterCreate(inspectionFile) {
        const Equipment = db.models.Equipment;
        const EquipmentAttribute = db.models.EquipmentAttribute;
        const InspectionRecord = db.models.InspectionRecord;
        let equipments = await Equipment.findAll({
          include: [{
            model: EquipmentAttribute
          }],
          order: [
            ['id', 'ASC']
          ]
        });
        let recordArr = [];
        for( let equipment of equipments ) {
          for( let attribute of equipment.EquipmentAttributes) {
            recordArr.push({
              value: attribute.value,
              state: null,
              label: equipment.label,
              InspectionFileOid: inspectionFile.oid,
              EquipmentAttributeId: attribute.id,
            });
          }
        }
        await InspectionRecord.bulkCreate(recordArr);  // 666啊，一次性请求真好
      }
    },
    associate(models) {
      models.InspectionFile.hasMany(models.InspectionRecord);
    }
  });
};
